package com.atguigu.study.service.impl;

import com.atguigu.study.annotations.MyRedisCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.study.entities.User;
import com.atguigu.study.service.UserService;
import com.atguigu.study.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
* @author 向佳怡
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-31 11:51:38
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
//    redisd里存的信息一定要有一个key前缀，这里设为user：
    public static final String CACHE_KEY_USER = "user:";

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean save(User user) {
        boolean retValue = false;
            log.info("插入之前user:{}", user);
            retValue = super.save(user);  // 数据库操作
            log.info("插入之后user:{}", user);
            log.info("======================");

            if (retValue) {
                user = this.userMapper.selectById(user.getId());  // 重新查询
//                缓存key，往mysql里面插入成功后再从mysql查询出来
                String key = CACHE_KEY_USER + user.getId();
                redisTemplate.opsForValue().set(key, user);  // Redis 操作
            }

        return retValue;
    }

//    @Override
//    public User getById(Serializable id) {
////        根据id查用户信息的方法
//        User user = null;
////        第一步：根据[user:${id}]从redis里面找
//        String key = CACHE_KEY_USER + id;
////        将从Redis里查询到的结果类型转换为user
//        user = (User) redisTemplate.opsForValue().get(key);
//        if (user == null){
////            从mysql里面查出来user
//            user = this.userMapper.selectById(id);
//
////            如果mysql有，redis没有
//            if (user != null){
////     把mysql捞到的数据写入redis，方便下次查询能redis命中。
//                redisTemplate.opsForValue().set(key,user);
//            }
//
//        }
//        return user;
//    }

    @Override
    @MyRedisCache(keyPrefix="user",matchValue = "#id")
    public User getById(Serializable id){
        return this.userMapper.selectById(id);
    }

}




